<template>
    <Editor :init="init" v-model="htmls" />
    <!-- api-key='your-api-key' -->
</template>

<script setup>
import { ref, toRefs, getCurrentInstance, watch, reactive } from 'vue'
let { proxy } = getCurrentInstance()
//引入tinymce编辑器
import tinymce from 'tinymce/tinymce' //这个若没有，主内容就没有了
import 'tinymce/themes/silver/theme' //这个若没有，就啥也显示不了了
import Editor from '@tinymce/tinymce-vue'

import 'tinymce/plugins/autosave' //自动存稿
import 'tinymce/plugins/code'     //编辑源码
import 'tinymce/plugins/codesample'  //代码示例
import 'tinymce/plugins/fullscreen'  //全屏
import 'tinymce/plugins/table'    //表格
import 'tinymce/plugins/hr'       //横线
import 'tinymce/plugins/link'     //链接
import 'tinymce/plugins/charmap'  //特殊符号
import 'tinymce/plugins/preview'  //预览
import 'tinymce/plugins/image'    //图片
import 'tinymce/plugins/media'    //视频
import 'tinymce/plugins/imagetools'  //图片编辑工具，选中图片后可以做操作
import 'tinymce/plugins/wordcount';
import 'tinymce/plugins/advlist';  //支持列表
import 'tinymce/plugins/lists';    //支持列表
import '../../public/tinymce/axupimgs/plugin'

const emit = defineEmits(['update:value']) //此处要完全对应，采用固定的update:prop属性
const props = defineProps({
    value:  { type: String, default: "", require: true },
    height: { type: [Number, String], required: false, default: 360 },
    width:  { type: [Number, String], required: false, default: '100%' },
    readOnly: { type: Boolean, default: false },
    placeholder: { type: String, default: "在这里输入文字" },
    maxsize: { type: Number, default: 1024 * 1024 * 5 }, //单位K，默认5120K，即5M
    maxwidth: { type: Number, default: 750 },
    maxheight: { type: Number, default: 750 },
    background: { type: String, default: "" },
    toolbar: { type: Array, default: ['undo redo | bold italic underline strikethrough | forecolor backcolor fontsizeselect fontselect | bullist numlist alignleft aligncenter alignright | link image axupimgs media table | blockquote removeformat code codesample hr charmap preview fullscreen']} 
})
let obj = reactive({
    htmls: props.value,
})
const init = {
    base_url:"/tinymce", //它控制显示图标
    skin_url: '/tinymce/skins/ui/oxide', //没有皮肤，什么都不会有
    language: 'zh_CN',  //语言类型
    height: props.height,
    width: props.width,
    readOnly: props.readOnly,
    placeholder: props.placeholder,
    // inline: true, //内联模式，会有问题，不要启用
    // statusbar: false, //这是完全去掉状态栏
    // elementpath: false,  //元素路径是否显示
    branding: false,  //tiny技术支持信息是否显示
    deprecation_warnings: false, //当前版本，加载imagetools会引发警告，加这个去掉
    plugins: "code codesample autosave fullscreen table hr link charmap preview image axupimgs media imagetools wordcount lists advlist", //axupimgs
    toolbar: props.toolbar,
    content_style: "img {max-width:100%;}", //限制图片超大
    // content_css: 'tinymce/tinymce_progress.css',  //以css文件方式自定义可编辑区域的css样式，css文件需自己创建并引入
    autosave_interval: "20s", //自动保存
    fontsize_formats: '12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px',  //字体大小
    font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',  //字体样式
    // lineheight_formats: "0.5 0.8 1 1.2 1.5 1.75 2 2.5 3 4 5",  //行高配置，也可配置成"12px 14px 16px 20px"这种形式

    setup: function (editor) { //修改默认字体和字号
        editor.on('init', function (e) {
            this.getBody().style.fontSize = '14px';
            this.getBody().style.fontFamily = '微软雅黑';
        });
    },
    images_upload_handler: function (blobInfo, succFun, failFun) {
        var file = blobInfo.blob();//转化为易于理解的file对象
        const isLimit = file.size < props.maxsize
        if (!isLimit) {
            proxy.elMessageMixin(`不能超过${props.maxsize/file.size}M`, 'error')
            return
        }

        //检查完成，可以上传
        let formData = new FormData(); //这样可以给form参数了
        formData.append("type", file.type);
        formData.append("file", file);
        if (props.maxwidth > 0) formData.append("maxheight", props.maxwidth);
        if (props.maxheight > 0) formData.append("maxwidth", props.maxheight);
        if (props.background != "") formData.append("background", props.background);

        proxy.$ajax({
            baseURL: "",
            url: proxy.$setting.globalUrl.uploadserver,
            data: formData,
            isUploadFile: true,
            bfLoading: false,
            timeout: 0,
            progress: p => { }
        }).then(res => {
            if(res.success){
                succFun(`${proxy.$setting.globalUrl.upload}/${res.filename}`);
            }else{
                failFun(`上传失败：${res.err}`)
                // proxy.elMessageMixin("", 'error')
            }
        }).catch(e => failFun(e))
    },
    file_picker_types: 'file image media', //允许上传这些
    file_picker_callback: (callback, value, meta) => {
        let filetype = ""
        switch(meta.filetype){
            case 'image': filetype='.jpg,.jpeg,.png,.gif'; break;
            case 'media': filetype='.mp3,.mp4'; break;
            case 'file': break;
            default: break;
        }
        //模拟出一个input用于添加本地文件
        let input = document.createElement('input');
        input.setAttribute('type', 'file');
        if (filetype != "") input.setAttribute('accept', filetype);
        input.click();
        input.onchange = e => {
            let file = e.srcElement.files[0]
            const isLimit = file.size < props.maxsize
            if (!isLimit) {
                proxy.elMessageMixin(`不能超过${props.maxsize/file.size}M`, 'error')
                return
            }

            //检查完成，可以上传
            let formData = new FormData(); //这样可以给form参数了
            formData.append("type", file.type);
            formData.append("file", file);
            if (props.maxwidth > 0) formData.append("maxheight", props.maxwidth);
            if (props.maxheight > 0) formData.append("maxwidth", props.maxheight);
            if (props.background != "") formData.append("background", props.background);

            // tinyMCE.activeEditor.setProgressState(true); //这一般用在禁用，但有弹出杠时，无效
            tinymce.DOM.$(".tox-dialog .tox-dialog__footer").prepend('<span></span>') //最终只能用jquery的方式实现进度
            // console.log(tinymce.activeEditor.editorUpload)
            // var notification = tinymce.activeEditor.notificationManager.open({
            //     text: '上传中，请稍候',
            //     progressBar: true
            // });
            // console.log(notification)
            proxy.$ajax({
                baseURL: "",
                url: proxy.$setting.globalUrl.uploadserver,
                data: formData,
                isUploadFile: true,
                bfLoading: false,
                timeout: 0,
                progress: p => {
                    // notification.progressBar.value(p.loaded / p.total * 100 | 0);
                    tinymce.DOM.$(".tox-dialog .tox-dialog__footer span").html("上传中... "+(p.loaded / p.total * 100 | 0) + '%')
                }
            }).then(res => {
                // tinymce.activeEditor.notificationManager.close();
                tinymce.DOM.$(".tox-dialog .tox-dialog__footer span").remove()
                switch(meta.filetype){
                    case 'image': callback(`${proxy.$setting.globalUrl.upload}/${res.filename}`, {alt: file.name}); break;
                    case 'media': callback(`${proxy.$setting.globalUrl.upload}/${res.filename}`, {source2: file.name, poster: ''}); break;
                    case 'file': callback(`${proxy.$setting.globalUrl.upload}/${res.filename}`, {text: file.name}); break;
                    default: break;
                }
            }).catch(() => tinymce.DOM.$(".tox-dialog .tox-dialog__footer span").remove())
        }
    }
}
watch(
    () => obj.htmls,
    (val) => emit('update:value', val)
)
watch(
    () => props.value,
    (val) => obj.htmls = val
)
let { htmls } = toRefs(obj)
</script>

<style scoped>
</style>